package io.ImageDownloader;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {

    // 从 URL 下载图片并保存到指定路径
    public static void saveImage(String urlStr, String savePath) throws IOException {
        URL url = new URL(urlStr); // 创建 URL 对象
        try (InputStream in = url.openStream(); // 网络输入流
             FileOutputStream fos = new FileOutputStream(savePath)) { // 本地文件输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }

    // 检查目录是否存在，不存在则创建
    public static void ensureDirectoryExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建多级目录
        }
    }

    // 记录日志到 download_log.txt
    public static void appendLog(String url, String savePath) {
        try (FileWriter fw = new FileWriter("download_log.txt", true)) {
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            fw.write(time + " | " + url + " | " + savePath + "\n");
        } catch (IOException e) {
            System.out.println("写入日志失败：" + e.getMessage());
        }
    }
}